package com.taiyi.renaissancemall.ui.main.imagegoodlist

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.taiyi.renaissancemall.R
import com.taiyi.renaissancemall.Utils.FlowLayoutManager
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.loadRound
import com.taiyi.renaissancemall.adapter.AdapterManager
import com.taiyi.renaissancemall.adapter.baseadapter.MultiItemTypeAdapter
import com.taiyi.renaissancemall.base.BaseActivity
import com.taiyi.renaissancemall.bean.FindBrandListBean
import com.taiyi.renaissancemall.bean.ImageGoodsListBean
import com.taiyi.renaissancemall.bean.SearchKindBean
import com.taiyi.renaissancemall.ui.main.goodsdetail.GoodsDetailActivity
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import kotlinx.android.synthetic.main.activity_goods_detail.*
import kotlinx.android.synthetic.main.activity_image_goods_list.*
import kotlinx.android.synthetic.main.activity_image_goods_list.bvPriceTv
import kotlinx.android.synthetic.main.activity_image_goods_list.priceTv
import kotlinx.android.synthetic.main.activity_image_goods_list.top
import kotlinx.android.synthetic.main.base_top_white_background_layout.*

class ImageGoodsListActivity : BaseActivity<ImageGoodsListView, ImageGoodsListPresent>(),
    ImageGoodsListView, SpringView.OnFreshListener, MultiItemTypeAdapter.OnItemClickListener {

    var pageNo = 1
    lateinit var dialog: Dialog
    var data = mutableListOf<ImageGoodsListBean.ComlistBean>()
    lateinit var dialogTagFlowLayout: TagFlowLayout
    lateinit var tv1: TextView
    lateinit var tv2: TextView
    lateinit var tv3: TextView
    lateinit var tv4: TextView
    lateinit var tv5: TextView
    lateinit var determineTv: TextView
    lateinit var resetTv: TextView
    lateinit var lowPriceEt: EditText
    lateinit var maxPriceEt: EditText
    var searchContent = ""
    var sale = ""
    var price = ""
    var bv = ""
    var myCategoryId = ""
    var isSelectPrice = false
    var isSelectBv = false
    var isSelectSale = false
    var selBrandIds = ""

    override fun getLayoutId(): Int = R.layout.activity_image_goods_list
    var brandList = mutableListOf<FindBrandListBean.BrandlistBean>()

    override fun initPresenter(): ImageGoodsListPresent = ImageGoodsListPresent()

    override fun initViews(savedInstanceState: Bundle?) {
        titleTv.text = intent.getStringExtra("labelName")
        if (intent.getStringExtra("categoryId") != null) {
            myCategoryId = intent.getStringExtra("categoryId")
        }
        var source = intent.getIntExtra("source", 0)
        if (source == 1) {
            var topImg = intent.getStringExtra("topImg")
            iv.loadRound(topImg)
        }
        comprehensiveTv.isSelected = true
        springView.header = DefaultHeader(this)
        springView.footer = DefaultFooter(this)
        springView.setGive(SpringView.Give.BOTH)
        springView.type = SpringView.Type.FOLLOW
        springView.setListener(this)

        var imageProductListAdapter = AdapterManager.getImageProductListAdapter(this, data)
        recyclerView.run {
            layoutManager = LinearLayoutManager(this@ImageGoodsListActivity)
            adapter = imageProductListAdapter
        }
        imageProductListAdapter.setOnItemClickListener(this)
        backIv.setOnClickListener { finish() }
        appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { p0, p1 ->
            springView.isEnable = p1 == 0
        })
        dialog = Dialog(this, R.style.MyDialog)
        var dialogView =
            LayoutInflater.from(this).inflate(R.layout.good_class_filter_dialog_layout2, null)
        dialogTagFlowLayout = dialogView.findViewById(R.id.tagFlowLayout)

        tv1 = dialogView.findViewById(R.id.tv1)
        tv2 = dialogView.findViewById(R.id.tv2)
        tv3 = dialogView.findViewById(R.id.tv3)
        tv4 = dialogView.findViewById(R.id.tv4)
        tv5 = dialogView.findViewById(R.id.tv5)
        determineTv = dialogView.findViewById(R.id.determineTv)
        resetTv = dialogView.findViewById(R.id.resetTv)
        lowPriceEt = dialogView.findViewById(R.id.lowPriceEt)
        maxPriceEt = dialogView.findViewById(R.id.maxPriceEt)
        dialog.setContentView(dialogView)
        dialog.setCanceledOnTouchOutside(true)
    }

    override fun initData() {
        showProgress()
        presenter.getProductList()
        presenter.getKindList()
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(top).init()
    }

    override fun initEvent() {
        tv1.setOnClickListener {
            update()
            tv1.isSelected = true
            lowPriceEt.setText("0")
            maxPriceEt.setText("199")
        }
        tv2.setOnClickListener {
            update()
            tv2.isSelected = true
            lowPriceEt.setText("200")
            maxPriceEt.setText("499")
        }
        tv3.setOnClickListener {
            update()
            tv3.isSelected = true
            lowPriceEt.setText("500")
            maxPriceEt.setText("799")
        }
        tv4.setOnClickListener {
            update()
            tv4.isSelected = true
            lowPriceEt.setText("800")
            maxPriceEt.setText("999")
        }
        tv5.setOnClickListener {
            update()
            tv5.isSelected = true
            lowPriceEt.setText("1000")
            maxPriceEt.setText("")
        }
        comprehensiveTv.setOnClickListener {
            //综合
            sale = ""
            price = ""
            bv = ""
            isSelectSale = false
            isSelectPrice = false
            isSelectBv = false
            salesIv.setImageResource(R.mipmap.price_dsc_iv)
            priceIv.setImageResource(R.mipmap.price_dsc_iv)
            bvIv.setImageResource(R.mipmap.price_dsc_iv)
            salesTv.isSelected = false
            priceTv.isSelected = false
            bvPriceTv.isSelected = false
            filterTv.isSelected = false
            comprehensiveTv.isSelected = true
            pageNo = 1
            showProgress()
            presenter.getProductList()
        }
        salesTv.setOnClickListener {
            //销量
            price = ""
            bv = ""
            isSelectSale = !isSelectSale
            isSelectPrice = false
            isSelectBv = false
            priceIv.setImageResource(R.mipmap.price_dsc_iv)
            bvIv.setImageResource(R.mipmap.price_dsc_iv)

            if (!isSelectSale) {
                sale = "1"
                salesIv.setImageResource(R.mipmap.price_asc_iv)
            } else {
                sale = "2"
                salesIv.setImageResource(R.mipmap.price_dsc_iv)
            }
            comprehensiveTv.isSelected = false
            priceTv.isSelected = false
            bvPriceTv.isSelected = false
            filterTv.isSelected = false
            salesTv.isSelected = true
            pageNo = 1
            showProgress()
            presenter.getProductList()
        }
        priceTv.setOnClickListener {
            //价格
            sale = ""
            bv = ""
            isSelectPrice = !isSelectPrice
            isSelectSale = false
            isSelectBv = false
            salesIv.setImageResource(R.mipmap.price_dsc_iv)
            bvIv.setImageResource(R.mipmap.price_dsc_iv)
            if (!isSelectPrice) {
                price = "1"
                priceIv.setImageResource(R.mipmap.price_asc_iv)
            } else {
                price = "2"
                priceIv.setImageResource(R.mipmap.price_dsc_iv)
            }
            comprehensiveTv.isSelected = false
            salesTv.isSelected = false
            bvPriceTv.isSelected = false
            filterTv.isSelected = false
            priceTv.isSelected = true
            pageNo = 1
            showProgress()
            presenter.getProductList()
        }
        bvPriceTv.setOnClickListener {
            //BV
            sale = ""
            price = ""
            isSelectBv = !isSelectBv
            isSelectSale = false
            isSelectPrice = false
            salesIv.setImageResource(R.mipmap.price_dsc_iv)
            priceIv.setImageResource(R.mipmap.price_dsc_iv)
            if (!isSelectBv) {
                bv = "1"
                bvIv.setImageResource(R.mipmap.price_asc_iv)
            } else {
                bv = "2"
                bvIv.setImageResource(R.mipmap.price_dsc_iv)
            }
            comprehensiveTv.isSelected = false
            salesTv.isSelected = false
            priceTv.isSelected = false
            filterTv.isSelected = false
            bvPriceTv.isSelected = true
            pageNo = 1
            showProgress()
            presenter.getProductList()
        }
        filterTv.setOnClickListener {
            //筛选
            dialog.show()
//            vv.visibility = VISIBLE
//            filterLayout.visibility = VISIBLE
        }


    }

    fun update() {
        tv1.isSelected = false
        tv2.isSelected = false
        tv3.isSelected = false
        tv4.isSelected = false
        tv5.isSelected = false
    }

    override fun onSuccess(imageGoodsListBean: ImageGoodsListBean?) {
        hideProgress()
        springView.onFinishFreshAndLoad()
        iv.loadRound(imageGoodsListBean?.xunchimg!!)
        var comlist = imageGoodsListBean?.comlist
        if (pageNo == 1)
            data.clear()
        data.addAll(comlist)
        recyclerView.adapter?.notifyDataSetChanged()

    }

    override fun onFailure(msg: String?) {
        hideProgress()
        springView.onFinishFreshAndLoad()
        toast(msg)
    }

    override fun getContent(): String = searchContent
    override fun getBrandIds(): String = selBrandIds

    override fun getKindListSuccess(list: FindBrandListBean) {
        var brandlist = list.brandlist
//        dialogRecyclerView.run {
//            //            layoutManager = FlowLayoutManager(this@ImageGoodsListActivity, true)
//            layoutManager = GridLayoutManager(this@ImageGoodsListActivity, 3)
//            adapter = TypeListAdapter(this@ImageGoodsListActivity, brandlist)
//        }
        var mInflater = LayoutInflater.from(this)
        dialogTagFlowLayout.adapter =
            object : TagAdapter<FindBrandListBean.BrandlistBean>(brandlist) {
                override fun getView(
                    parent: FlowLayout?,
                    position: Int,
                    t: FindBrandListBean.BrandlistBean?
                ): View {
                    var tv = mInflater.inflate(
                        R.layout.new_flow_tv_item_layout,
                        dialogTagFlowLayout,
                        false
                    )
                        .findViewById<TextView>(R.id.tv)
                    tv.text = t?.brandname
                    return tv
                }

            }




        determineTv.setOnClickListener {
            searchContent = ""
            selBrandIds = ""
            var sb = StringBuffer()
            var selectedList = dialogTagFlowLayout.selectedList
            var iterator = selectedList.iterator()
            while (iterator.hasNext()) {
                sb.append(",${brandlist[iterator.next()].brandid}")
            }
//            if (brandlist != null || brandlist?.size!! > 0) {
//                for (item in brandlist) {
//                    if (item.isChoose) {
////                        Log.i("ssssssssss", "------${item.categoryname}")
//                        sb.append(",${item.brandid}")
//                    }
//                }
//            }
            if (sb.toString().isNotEmpty()) {
                var substring = sb.substring(1)
                searchContent = substring
                selBrandIds = substring
            }
            dialog.dismiss()
            showProgress()
            springView.callFresh()
        }
        resetTv.setOnClickListener {
            //重置
            if (brandlist != null || brandlist?.size!! > 0) {
                for (item in brandlist) {
                    item.isChoose = false
                }
            }

            dialogTagFlowLayout.selectedList.clear()

            dialogTagFlowLayout.adapter.notifyDataChanged()
//            dialogRecyclerView?.adapter?.notifyDataSetChanged()

            update()
            lowPriceEt.setText("")
            maxPriceEt.setText("")
        }

    }

    override fun getBvSort(): String = bv

    inner class TypeListAdapter(
        context: Context,
        var data: MutableList<FindBrandListBean.BrandlistBean>
    ) :
        RecyclerView.Adapter<TypeListAdapter.TypeListHolder>() {
        var layoutInflater: LayoutInflater = LayoutInflater.from(context)

        inner class TypeListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var tv = itemView.findViewById<TextView>(R.id.tv)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TypeListHolder {
            var view = layoutInflater.inflate(R.layout.new_flow_tv_item_layout, null)
            return TypeListHolder(view)
        }

        override fun getItemCount(): Int = when (data) {
            null -> 0
            else -> data.size
        }

        override fun onBindViewHolder(holder: TypeListHolder, position: Int) {
            holder.tv.text = data[position].brandname
            holder.tv.isSelected = data[position].isChoose
            holder.tv.setOnClickListener {
                data[position].isChoose = !data[position].isChoose
                holder.tv.isSelected = data[position].isChoose
                notifyDataSetChanged()
            }
        }
    }

    override fun getLabelId(): String = intent.getStringExtra("labelId")
    override fun getSaleSort(): String = sale

    override fun getLowPrice(): String = lowPriceEt.text.toString()

    override fun getMaxPrice(): String = maxPriceEt.text.toString()

    override fun getPageNum(): String = pageNo.toString()
    override fun getCategoryId(): String = myCategoryId
    override fun getPriceSort(): String = price

    override fun onLoadmore() {
        pageNo += 1
        presenter.getProductList()
    }

    override fun onRefresh() {
        pageNo = 1
        presenter.getProductList()
    }

    override fun onItemLongClick(
        view: View?,
        holder: RecyclerView.ViewHolder?,
        position: Int
    ): Boolean {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onItemClick(view: View?, holder: RecyclerView.ViewHolder?, position: Int) {
        var intent = Intent(this, GoodsDetailActivity::class.java)
        var bundle = Bundle()
        bundle.putString("commodityId", data[position].commodityid)
        intent.putExtras(bundle)
        startActivity(intent)
    }


}
